//@author A0106044W
package logic;

import java.util.ArrayList;
import java.util.logging.Level;

import commandInfo.CommandInfo;
import commandInfo.RemoveFilterCommandInfo;
import storage.Task;

/**
 * 
 *
 * 	       Sothearith Sreang
 *         All of the Logic part is written by me.
 * 
 */

public class AddFilterHandler extends OperationHandler {
	
	ArrayList<Task> filterTasksList;
	
	private static final String SUCCESSFUL_UNDO = "%1d tasks are removed successfully";
	private static final String UNSUCCESSFUL_UNDO = "Task that are retrieved from CommandHistory cannot be found in storage.";
	
	// for undo, redo filter add operation
	public AddFilterHandler(CommandInfo commandInfoP){
		super();
		initializeFilterTasksList();
		getTasksList(commandInfoP);
	}
	
	public String undo(){
		ArrayList<Task> cloneTasksList =  new ArrayList<Task>();
		
		for(Task task : filterTasksList) {
			addTask(task, cloneTasksList);
		}
		
		super.commandInfo = new RemoveFilterCommandInfo(cloneTasksList);
		String feedback = String.format(SUCCESSFUL_UNDO, filterTasksList.size());
		
		return feedback;
	}
	
	// Next level abstraction
	// These methods are called by AddFilterHandler constructor
	
	private void addTask(Task task, ArrayList<Task> cloneTasksList) {
		boolean isSuccess = false;
		
		try{
			Task taskClone = getTaskClone(task);
			isSuccess = super.storage.removeTask(task);
			
			if(isSuccess) {
				cloneTasksList.add(taskClone);
			} else {
				Logic.logger.log(Level.SEVERE, UNSUCCESSFUL_UNDO);
			}
			
		} catch(Exception e) {
			Logic.logger.log(Level.SEVERE, e.getMessage());
		}
	}

	private Task getTaskClone(Task task) {
		Task taskClone = null;
		
		try {
			taskClone = task.cloneSelf();
		} catch (Exception e) {
			Logic.logger.log(Level.SEVERE, e.getMessage());
		}
		
		return taskClone;
	}

	private void initializeFilterTasksList() {
		filterTasksList = new ArrayList<Task>();
	}

	private void getTasksList(CommandInfo commandInfoP){
		ArrayList<Task> cloneTaskList = commandInfoP.getUpdatedTasksList();
		
		for(Task taskClone: cloneTaskList) {
			Task task = super.getTask(taskClone);
			assert task != null;
			filterTasksList.add(task);
		}
	}

}
